package cn.cheneyjoo.sqlsession;

import cn.cheneyjoo.config.BoundSql;
import cn.cheneyjoo.model.Configuration;
import cn.cheneyjoo.model.MappedStatement;
import cn.cheneyjoo.utils.GenericTokenParser;
import cn.cheneyjoo.utils.ParameterMapping;
import cn.cheneyjoo.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        Connection connection = configuration.getDataSource().getConnection();
        String sqlText = mappedStatement.getSqlText();

        // 获取转义好的SQL语句
        BoundSql boundSql = getBoundSql(sqlText);

        // 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        // 设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            // 反射 根据字段名获取字段信息
            Field field = parameterClass.getDeclaredField(content);
            // 暴力访问
            field.setAccessible(true);
            // 获取指定对象中的指定字段中的值 由于SQL语句中的parameterType 只是会配置单个对象信息 所以直接获取第一个即可 就是params[0]
            Object o = field.get(params[0]);

            // 设置指定位置指定的值
            preparedStatement.setObject(i + 1, o);
        }

        // 执行SQL
        ResultSet resultSet = preparedStatement.executeQuery();

        // 封装返回结果集
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        List<Object> objects = new ArrayList<>();
        while (resultSet.next()) {
            Object resultTypeObject = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 获取字段名
                String columnName = metaData.getColumnName(i);
                // 获取字段值
                Object columnValue = resultSet.getObject(columnName);
                // 使用内省，根据数据库表和JavaBean的对应关系 进行封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(resultTypeObject, columnValue);
            }
            objects.add(resultTypeObject);
        }

        return (List<E>) objects;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        Connection connection = configuration.getDataSource().getConnection();
        String sqlText = mappedStatement.getSqlText();

        // 获取转义好的SQL语句
        BoundSql boundSql = getBoundSql(sqlText);

        // 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        // 设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            // 如果是基础类型 那么就直接取值
            if (parameterClass.getName().startsWith("java.lang")) {
                preparedStatement.setObject(i + 1, params[0]);
            } else {
                // 反射 根据字段名获取字段信息
                Field field = parameterClass.getDeclaredField(content);
                // 暴力访问
                field.setAccessible(true);
                // 获取指定对象中的指定字段中的值 由于SQL语句中的parameterType 只是会配置单个对象信息 所以直接获取第一个即可 就是params[0]
                Object o = field.get(params[0]);

                // 设置指定位置指定的值
                preparedStatement.setObject(i + 1, o);
            }

        }

        // 执行SQL
        return preparedStatement.executeUpdate();
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null) {
            return Class.forName(parameterType);
        }
        return null;
    }

    private BoundSql getBoundSql(String sqlText) {
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        String parseSql = tokenParser.parse(sqlText);
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }


}
